package com.qyhl.webtv.basiclib.base;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.SimpleImmersionOwner;
import com.gyf.immersionbar.components.SimpleImmersionProxy;
import com.qyhl.webtv.basiclib.R;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.ToastUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.weavey.loading.lib.LoadingLayout;

import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;

/**
 * 基础 Fragment
 *
 * @author helin
 * @date 2019年3月1日11:39:24
 */
public abstract class BaseFragment extends Fragment implements SimpleImmersionOwner {

    /**
     * ImmersionBar代理类
     */
    private SimpleImmersionProxy mSimpleImmersionProxy = new SimpleImmersionProxy(this);
    private View view;
    private boolean isCreate = false;
    private boolean isVisible = false;
    private boolean isFirstVisible = true;
    private LoadingDialog.Builder mBuilder;
    public ImmersionBar im;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = createView(inflater, container, savedInstanceState);
            ButterKnife.bind(this, view);
            create();
            setListener();
            isCreate = true;
            callbackVisible(true);
        }
        return view;
    }


    /**
     * Fragment显示或隐藏时调用，需要注意此方法会在onCreateView之前调用
     * 使用viewpager动态加载时调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isVisible = true;
        }
        callbackVisible(isVisibleToUser);
        mSimpleImmersionProxy.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mSimpleImmersionProxy.onActivityCreated(savedInstanceState);
    }


    /**
     * Fragment显示或隐藏时调用，需要注意此方法会在onCreateView之前调用
     * fragment使用show和hint方法时调用
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //不可见
        } else {
            //可见
        }
        mSimpleImmersionProxy.onHiddenChanged(hidden);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mSimpleImmersionProxy.onConfigurationChanged(newConfig);
    }


    /**
     * 做一下逻辑处理
     * 确保onFirstVisible在onCreateView之后
     */
    private void callbackVisible(boolean isVisibleToUser) {
        if (isCreate && isVisible) {
            if (isVisibleToUser) {
                if (isFirstVisible) {
                    onFirstVisible();
                    isFirstVisible = false;
                } else {
                    onVisible();
                }
            } else {
                onHide();
            }
        }
    }
    @Override
    public void onDestroy() {
        isVisible = false;
        isCreate = false;
        if (view!=null&&view.getParent() != null) {
            ((ViewGroup) view.getParent()).removeView(view);
        }
        super.onDestroy();
        mSimpleImmersionProxy.onDestroy();
    }


    protected View getInflateView() {
        return view;
    }


    /**
     * 隐藏软键盘
     */
    public void hideInput() {
        InputMethodManager imm = (InputMethodManager) mContent.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(((Activity)mContent).getWindow().getDecorView().getWindowToken(), 0);

    }
    /**
     * 显示加载动画
     */
    protected void showLoading() {
        mBuilder = new LoadingDialog.Builder(getActivity());
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    /**
     * 显示加载动画
     *
     * @param title 加载提示
     */
    protected void showLoading(String title) {
        mBuilder = new LoadingDialog.Builder(getActivity());
        mBuilder.setTitle(title);
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    /**
     * 显示加载动画
     *
     * @param percent 加载进度
     */
    protected void showLoading(int percent) {
        mBuilder = new LoadingDialog.Builder(getActivity());
        mBuilder.setProgress(percent);
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContent= (Activity) context;
    }
    public  static  final  int  ERROR =1;
    public  static  final  int  INFO =2;
    public  static  final  int  SUCCESS =3;
    public Activity mContent;
    /**
     * 展示Toast
     *
     * @param msg
     */
    public void showToast(String msg,int type) {
        ToastUtils.showToast(mContent,msg);
    }

    /**
     * 显示加载动画
     *
     * @param title   加载提示
     * @param percent 加载进度
     */
    protected void showLoading(String title, int percent) {
        mBuilder = new LoadingDialog.Builder(getActivity());
        mBuilder.setTitle(title);
        mBuilder.setProgress(percent);
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    /**
     * 加载错误
     *
     * @param message
     */
    public void errorLoad(String message, LoadingLayout mLoading){
        mLoading.setErrorText(message);
        mLoading.setErrorImage(R.drawable.error_content);
        mLoading.setStatus(LoadingLayout.Error);
    }


    public void emptyLoad(LoadingLayout mLoading){
        mLoading.setEmptyText("暂无内容");
        mLoading.setEmptyImage(R.drawable.empty_comment);
        mLoading.setStatus(LoadingLayout.Empty);
    }

    /**
     * 隐藏加载动画
     */
    protected void dismissLoading() {
        if (mBuilder != null) {
            mBuilder.dismiss();
        }
    }

    /**
     * 提示
     *
     * @param msg 提示信息
     */
    protected void showToast(final String msg) {
        ToastUtils.showToast(getActivity(),msg);
    }



    /**
     * 以下前4个方法按顺序依次调用
     * 创建视图
     */
    protected abstract View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    /**
     * 相当于Fragment创建完毕，这里可以做初始化操作，可以使用控件
     */
    protected abstract void create();

    /**
     * 设置监听
     */
    protected abstract void setListener();

    /**
     * Fragment第一次可见时调用，如果不是必须的初始化操作可以放在这里，避免多个fragment同时加载资源
     */
    protected abstract void onFirstVisible();

    /**
     * Fragment每次可见时调用（第一次不调用）
     */
    protected abstract void onVisible();

    /**
     * Fragment每次不可见时调用
     */
    protected abstract void onHide();

    /**
     * 是否可以实现沉浸式，当为true的时候才可以执行initImmersionBar方法
     * Immersion bar enabled boolean.
     *
     * @return the boolean
     */
    @Override
    public boolean immersionBarEnabled() {
        return true;
    }

    @Override
    public void initImmersionBar() {
        im = ImmersionBar.with(this);
        im.keyboardEnable(true).init();
    }



}
